package org.nutz.mvc.view;

import com.ht.thymeleaf.ext.BuiDialect;
import org.nutz.ioc.Ioc;
import org.nutz.mvc.View;
import org.nutz.mvc.ViewMaker;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 薄成文 13-9-12 下午11:29
 * To change this template use File | Settings | File Templates.
 */
public class ThymeleafViewMaker implements ViewMaker {
    public static final TemplateEngine templateEngine = new TemplateEngine();
    private String encoding = "UTF-8";
    private String contentType = "text/html; charset=" + encoding;
    private String templateMode = "LEGACYHTML5";
    private String prefix = "/WEB-INF/tpl/";
    private String suffix = ".html";

    public ThymeleafViewMaker() {
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();

        // XHTML is the default mode, but we will set it anyway for better understanding of code
        templateResolver.setTemplateMode(templateMode);
        templateResolver.setPrefix(prefix);
        templateResolver.setSuffix(suffix);
        //templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCharacterEncoding(encoding);
        // Set template cache TTL to 1 hour. If not set, entries would live in cache until expelled by LRU
        templateResolver.setCacheTTLMs(Long.valueOf(3600000L));

        templateResolver.setCacheable(false);

        templateEngine.setTemplateResolver(templateResolver);
        templateEngine.addDialect(new BuiDialect());
    }

    @Override
    public View make(Ioc ioc, String type, String value) {
        if ("th".equalsIgnoreCase(type)) {
            return new ThymeleafView(templateEngine, value);
        }
        return null;  //To change body of implemented methods use File | Settings | File Templates.
    }
}
